package com.yudaxian.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yudaxian.common.HoneyLogs;
import com.yudaxian.common.enums.LogType;
import com.yudaxian.common.vo.Result;
import com.yudaxian.sys.entity.User;
import com.yudaxian.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yudaxian
 * @since 2023-09-21
 */
@Api(tags = {"用户接口列表"})
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @GetMapping("/all")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.list();
        return Result.success(users);
    }

    @HoneyLogs(operation = "登录", type = LogType.LOGIN)
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody User user) {
        Map<String, Object> data = userService.login(user);
        if (data != null) {
            return Result.success(data);
        }
        return Result.fail(20002, "用户名或密码错误");
    }

    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(@RequestParam("token") String token) {
        //根据token获取用户信息
        Map<String, Object> data = userService.getUserInfo(token);
        if (data != null) {
            return Result.success(data);
        }
        return Result.fail(20002, "token失效，请重新登录");
    }

    @HoneyLogs(operation = "退出", type = LogType.LOGOUT)
    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("X-Token") String token) {
        userService.logout(token);
        return Result.success();
    }

    @GetMapping("/list")
    public Result<Map<String, Object>> getUserList(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "pageNo") Integer pageNo,
            @RequestParam(value = "pageSize") Integer pageSize) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(username), User::getUsername, username);
        wrapper.eq(StringUtils.hasLength(phone), User::getPhone, phone);

        Page<User> page = new Page<>(pageNo, pageSize);
        userService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }
    @PostMapping("/add")
    //RequestBody，json转user对象，前端输入数据，传给后台json，再转成对象，存入数据库
    public Result<?> addUser(@RequestBody User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.addUser(user);
        return Result.success("新增成功");
    }

    @HoneyLogs(operation = "角色", type = LogType.UPDATE)
    @PutMapping("/update")
    //RequestBody，json转user对象，前端输入数据，传给后台json，再转成对象，存入数据库
    public Result<?> updateUser(@RequestBody User user) {
        user.setPassword(null);
        userService.updateUser(user);

        return Result.success("修改成功");
    }

    @GetMapping("{id}")
    public Result<User> getUserById(@PathVariable("id") Integer id) {
        User user = userService.getUserById(id);

        return Result.success(user);
    }

    @HoneyLogs(operation = "角色", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteUserById(@PathVariable("id") Integer id) {
        userService.deleteUserById(id);

        return Result.success("删除成功");
    }
}
